const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const connectDB = require('./db/db'); // 导入数据库连接函数
const session = require('express-session');
const myRouter=require('./routes/api/my')
const authRouter=require('./routes/api/auth')
const detailRouter=require('./routes/api/detail')
const discussRouter=require('./routes/api/discuss')
const serviceRouter=require('./routes/api/service')
const otherRouter=require('./routes/api/other')
const fs = require('fs');
const cors = require('cors');

const app = express();

const uploadDirs = ['uploads', 'uploads/avatars', 'uploads/covers'];
uploadDirs.forEach(dir => {
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
        console.log('✅ 创建目录:', dir);
    }
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use('/uploads', express.static('uploads'));
app.use(logger('dev'));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'my_secret_key', // 用于加密session的密钥（自定义一个字符串）
  resave: false, // 是否每次请求都重新保存session（建议false）
  saveUninitialized: false, // 是否保存未初始化的session（建议false）
  cookie: { 
    maxAge: 24 * 60 * 60 * 1000, // session有效期（这里设置为1天，单位毫秒）
    secure: false // 开发环境设为false（http可用），生产环境用https时设为true
  }
}));


app.use('/my', myRouter);
app.use('/api',authRouter)
app.use('/detail',detailRouter);
app.use('/discuss',discussRouter);
app.use('/',serviceRouter)
app.use('/',otherRouter)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.render('404')
});

// error handler
app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

// 仅连接数据库，不在这里启动服务器（交给 bin/www 处理）
connectDB()
  .then(() => console.log('数据库连接成功'))
  .catch(err => console.error('数据库连接失败:', err));

module.exports = app; // 导出 app 供 bin/www 使用